package com.xy.learn.springlearn.filter;

import com.xy.learn.springlearn.exception.NotAllowException;
import jakarta.annotation.Resource;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;

@WebFilter
@Component
public class PermissionFilter implements Filter {
    @Resource
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String token = httpServletRequest.getHeader("token");

        if (!"111".equals(token)) {
            // 手动异常处理，不然不会生效
            // throw new NotAllowException("没有授权"); 使用RestControllerAdvice拦截不到
            resolver.resolveException(httpServletRequest, (HttpServletResponse) servletResponse, null, new NotAllowException("没有授权"));
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
